package com.tengfei.mid_term;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    private EditText etUsr;
    private EditText etPwd;
    private Button loginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getSupportActionBar().setTitle("登录页");
        // 初始化界面
        initView();
        // 初始化数据
        initData();
    }


    private void initView() {
        etUsr = findViewById(R.id.stu_num);
        etPwd = findViewById(R.id.stu_pwd);
        loginBtn = findViewById(R.id.stu_login);
    }

    private void initData() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUsr.getText().toString().trim();
                String password = etPwd.getText().toString().trim();
                if (TextUtils.equals(username, "")) {
                    Toast.makeText(LoginActivity.this, "用户名为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.equals(password, "")) {
                    Toast.makeText(LoginActivity.this, "密码为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!TextUtils.equals(username, "admin")) {
                    Toast.makeText(LoginActivity.this, "用户名错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!TextUtils.equals(password, "admin")) {
                    Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                // 登录成功
                SharedPreferences spf = getSharedPreferences("user_info", MODE_PRIVATE);
                SharedPreferences.Editor edit = spf.edit();
                edit.putString("username", username);
                edit.putString("password", password);
                edit.apply();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                LoginActivity.this.finish();
            }

        });
    }
}